<script setup lang="ts">
import {
    getJobPage,
    getJob,
    addJob,
    updateJob,
    delJob
} from "@/api/job";

import { getDeptOptions } from "@/api/dept";

import { JobPageVO, JobForm, JobQuery } from "@/api/job/types";

defineOptions({
  name: "Job",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const jobFormRef = ref(ElForm);

const deptOptions = ref<OptionType[]>();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<JobQuery>({
  pageNum: 1,
  pageSize: 10,
});

const jobList = ref<JobPageVO[]>();

const dialog = reactive({ title: "",visible: false,});

const formData = reactive<JobForm>({
    name: "",
    deptId: undefined,
    sort: 1,
    enabled: 1,
});

const rules = reactive({
  name: [{ required: true, message: "请输入职级名称", trigger: "blur" }],
  deptId: [{ required: true, message: "请选择归属部门", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  enabled: [{ required: true, message: "请选择状态", trigger: "blur" }],
});


/** 查询 */
function handleQuery() {
  loading.value = true;
  getJobPage(queryParams)
    .then(({ data }) => {
        jobList.value = data.list;
        total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行checkbox 选中事件 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 打开角色表单弹窗 */
async function openDialog(jobId?: number) {
  await loadDeptOptions();
  dialog.visible = true;
  if (jobId) {
    dialog.title = "修改职级";
    getJob(jobId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增职级";
  }
}

/** 角色保存提交 */
function handleSubmit() {
    jobFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const jobId = formData.id;
      if (jobId) {
        updateJob(jobId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addJob(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  jobFormRef.value.resetFields();
  jobFormRef.value.clearValidate();
  formData.id = undefined;
  formData.sort = 1;
  formData.enabled = 1;
}

/** 删除角色 */
function handleDelete(jobId?: number) {
  const jobIds =  jobId?[jobId]:ids.value;
  if (!jobIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    delJob({'ids':jobIds})
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}
 
/** 获取部门下拉数据  */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptOptions.value = response.data
    // deptOptions.value = [
    //   {
    //     value: 0,
    //     label: "顶级部门",
    //     children: response.data,
    //   },
    // ];
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="name" label="职级名称">
          <el-input
            v-model="queryParams.name"
            placeholder="职级名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="openDialog()"><i-ep-plus />新增</el-button>
        <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()" ><i-ep-delete />删除</el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="jobList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="职级名称" prop="name" min-width="150" />
        <el-table-column label="归属部门" prop="dept.name" width="200" />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="80" prop="sort" />

        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="closeDialog"
    >
      <el-form
        ref="jobFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="选择归属部门"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="职级名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入职级名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="职级状态">
          <el-radio-group v-model="formData.enabled">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit"> 确 定 </el-button>
          <el-button @click="closeDialog"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>